from fastapi import APIRouter, Depends, HTTPException, status, Query
from sqlalchemy.orm import Session
from typing import Optional
from database import get_db
from models import User
from schemas import UserResponse, UserUpdate, UserListResponse
from utils.auth_utils import get_current_user, get_password_hash
from logger import logging

router = APIRouter(prefix="/api/admin/users", tags=["用户管理"])


@router.get("", response_model=UserListResponse, summary="获取用户列表")
async def get_users(
    skip: int = Query(0, ge=0, description="跳过的记录数"),
    limit: int = Query(10, ge=1, le=100, description="返回的记录数"),
    username: Optional[str] = Query(None, description="用户名搜索"),
    email: Optional[str] = Query(None, description="邮箱搜索"),
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user)
):
    """
    获取用户列表（支持分页和搜索）

    - **skip**: 跳过的记录数（分页）
    - **limit**: 返回的记录数（分页）
    - **username**: 用户名搜索关键字（可选）
    - **email**: 邮箱搜索关键字（可选）
    """
    try:
        # 构建查询
        query = db.query(User)

        # 添加搜索条件
        if username:
            query = query.filter(User.username.contains(username))
        if email:
            query = query.filter(User.email.contains(email))

        # 获取总数
        total = query.count()

        # 分页查询
        users = query.offset(skip).limit(limit).all()

        logging.info(f"管理员 {current_user.username} 查询用户列表，共 {total} 条记录")

        return UserListResponse(total=total, users=users)
    except Exception as e:
        logging.error(f"获取用户列表失败: {str(e)}")
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail="获取用户列表失败"
        )


@router.get("/{user_id}", response_model=UserResponse, summary="获取用户详情")
async def get_user(
    user_id: int,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user)
):
    """
    根据用户ID获取用户详情

    - **user_id**: 用户ID
    """
    try:
        user = db.query(User).filter(User.id == user_id).first()

        if not user:
            raise HTTPException(
                status_code=status.HTTP_404_NOT_FOUND,
                detail="用户不存在"
            )

        logging.info(f"管理员 {current_user.username} 查询用户 {user.username} 的详情")

        return user
    except HTTPException:
        raise
    except Exception as e:
        logging.error(f"获取用户详情失败: {str(e)}")
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail="获取用户详情失败"
        )


@router.put("/{user_id}", response_model=UserResponse, summary="更新用户信息")
async def update_user(
    user_id: int,
    user_update: UserUpdate,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user)
):
    """
    更新用户信息

    - **user_id**: 用户ID
    - **username**: 新用户名（可选）
    - **email**: 新邮箱（可选）
    - **password**: 新密码（可选）
    """
    try:
        # 查询用户
        user = db.query(User).filter(User.id == user_id).first()

        if not user:
            raise HTTPException(
                status_code=status.HTTP_404_NOT_FOUND,
                detail="用户不存在"
            )

        # 检查用户名是否已存在
        if user_update.username and user_update.username != user.username:
            existing_user = db.query(User).filter(
                User.username == user_update.username
            ).first()
            if existing_user:
                raise HTTPException(
                    status_code=status.HTTP_400_BAD_REQUEST,
                    detail="用户名已存在"
                )
            user.username = user_update.username

        # 检查邮箱是否已存在
        if user_update.email and user_update.email != user.email:
            existing_user = db.query(User).filter(
                User.email == user_update.email
            ).first()
            if existing_user:
                raise HTTPException(
                    status_code=status.HTTP_400_BAD_REQUEST,
                    detail="邮箱已存在"
                )
            user.email = user_update.email

        # 更新密码
        if user_update.password:
            user.hashed_password = get_password_hash(user_update.password)

        # 提交更改
        db.commit()
        db.refresh(user)

        logging.info(f"管理员 {current_user.username} 更新了用户 {user.username} 的信息")

        return user
    except HTTPException:
        raise
    except Exception as e:
        db.rollback()
        logging.error(f"更新用户信息失败: {str(e)}")
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail="更新用户信息失败"
        )


@router.delete("/{user_id}", summary="删除用户")
async def delete_user(
    user_id: int,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user)
):
    """
    删除用户

    - **user_id**: 用户ID
    """
    try:
        # 查询用户
        user = db.query(User).filter(User.id == user_id).first()

        if not user:
            raise HTTPException(
                status_code=status.HTTP_404_NOT_FOUND,
                detail="用户不存在"
            )

        # 防止删除自己
        if user.id == current_user.id:
            raise HTTPException(
                status_code=status.HTTP_400_BAD_REQUEST,
                detail="不能删除自己的账号"
            )

        username = user.username

        # 删除用户
        db.delete(user)
        db.commit()

        logging.info(f"管理员 {current_user.username} 删除了用户 {username}")

        return {"message": "用户删除成功", "username": username}
    except HTTPException:
        raise
    except Exception as e:
        db.rollback()
        logging.error(f"删除用户失败: {str(e)}")
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail="删除用户失败"
        )
